from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.neighbors import KNeighborsClassifier
import pickle
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np


with open("X", 'rb') as f:
    X = pickle.load(f)
    print(f"成功载入X：type: {type(X)}，shape: {np.shape(X)}")
with open("y", 'rb') as f:
    y = pickle.load(f)
    print(f"成功载入y：type: {type(y)}，shape: {np.shape(y)}")

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
clf = RandomForestClassifier()
clf.fit(X_train, y_train)
predicted = clf.predict(X_test)

# 打印混淆矩阵和分类报告
print(confusion_matrix(y_test, predicted))
print(classification_report(y_test, predicted))

img = cv.imread("zhangguorong.10001.jpg")
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img_gray = cv.equalizeHist(img_gray)  # 把图像的范围拉开
# 1. 创建级联分类器
face_cascade = cv.CascadeClassifier()
# 2. 引入训练好的可用于人脸识别的级联分类器模型
face_cascade.load("haarcascade_frontalface_alt.xml")
# 3. 用此级联分类器识别图像中的所有人脸信息，返回一个包含有所有识别的人联系系的列表
# 列表中每一个元素包含四个值：面部左上角的坐标(x,y) 以及面部的宽和高(w,h)
faces = face_cascade.detectMultiScale(img_gray)
names={0:"chenyixun",1:"linjunjie",2:"zhangguorong",3:"zhangxueyou",4:"zhoujielun"}

# 4. 为图像中的所有面部画框
for (x, y, w, h) in faces:
    cv.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
    face=cv.resize(img[y:y+h,x:x+w],(32,32))
    face=cv.cvtColor(face,cv.COLOR_BGR2GRAY).ravel()
    name=names[clf.predict([face])[0]]
    cv.putText(img, # 要显示字体的图片
              name, # 要显示的内容
              (x,y-10), # 要显示的位置
              cv.FONT_HERSHEY_SIMPLEX, # 要使用的字体 -> 一般英文字体
              1, # 字体放大倍数
              (0,255,0), # 字体颜色
              2) # 字体线条粗细

plt.figure(figsize=(10, 5))
plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))
plt.show()
